﻿/**
 * @class Dom
 * @singleton
 */
(function(){
var Dom = {
	/**
	 * document.getElementById的缩写
	 * @method _
	 * @param {string} s 元素ID
	 * @return {HTMLElement}
	 */
    _: function(s) {
        return document.getElementById(s);
    },
	/**
	 * getElementsByTagName的封装
	 * @method getByTagName
	 * @param {HTMLElement} parent 父结点
	 * @param {string} tag 标签名称
	 * @return {HTMLElements} 
	 */
    getByTagName: function(parent, tag) {
		if( !parent )
			return [];
        return parent.getElementsByTagName(tag);
    },
	/**
	 * getElementsByClassName的兼容封装
	 * @method getByClass
	 * @param {string} searchClass 类名
	 * @param {HTMLElement} node 父结点
	 * @param {string} tag 标签名称(可选)
	 * @return {HTMLElements}
	 */
	getByClass: function(searchClass,node,tag) {
        var classElements = [];
        if ( node == null )
                node = document;
        if ( tag == null )
                tag = '*';
        var els = node.getElementsByTagName(tag);
        var elsLen = els.length;
        var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
        for (var i = 0, j = 0; i < elsLen; i++) {
                if ( pattern.test(els[i].className) ) {
                        classElements[j] = els[i];
                        j++;
                }
        }
        return classElements;
	},
	
	/**
	 * 添加事件
	 * @method addEvt
	 * @param {HTMLElement} elm
	 * @param {string} en 事件名
	 * @param {Function} func 监听函数
	 */
    addEvt: function (elm, en, func) {
        if (elm.attachEvent)
            elm.attachEvent('on' + en, func, false);
        else if (elm.addEventListenner)
            elm.addEventListenner(en, func, false);
        else
            elm['on' + en] = func;
    },
	
	/**
	 * 添加类名
	 * @method addClass
	 * @param {HTMLElement} o
	 * @param {string} className
	 */
	addClass : function (o, className) {
		if (!o)
			return;
		o.className = className + " " + o.className;
	},

	/**
	 * 移除类名
	 * @method repalceClass
	 * @param {HTMLElement} o
	 * @param {string} className
	 */
	repalceClass : function (o, className) {
		if (!o)
			return;
		o.className = o.className.replace(new RegExp('^ *'+className+'(?:[ ]*|\\b)+','ig'), '');
	},
	
	uaMatch: function() {
		var rwebkit = /(webkit)[ \/]([\w.]+)/ig,
			ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/ig,
			rmsie = /(msie) ([\w.]+)/ig,
			rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/ig;
		var ua = navigator.userAgent.toLowerCase();

		var match = rwebkit.exec( ua ) ||
			ropera.exec( ua ) ||
			rmsie.exec( ua ) ||
			ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
			[];

		return { browser: match[1] || "", version: match[2] || "0" };
	},
	browser: {}
}

var uaMathcRst = Dom.uaMatch();
Dom.browser[ uaMathcRst['browser'] ] = true;
Dom.browser.version = uaMathcRst['version'];

Dom._t = Dom.getByTagName;

/**
 * 标签切换的方法
 * @method tabSwitch
 * @param {String} label 切换标签的父ID
 * @param {String} box   内容区域的父ID
 * @param {String} cls   类名
 */
Dom.tabSwitch = function(label, box, cls){
	var label = Dom._(label).children,
		box = Dom._(box).children,
		cls = cls || 'on';
	for(var i=0;i<label.length;i++){
		label[i].onclick = function() {
			Dom.repalceClass(this, cls);
			Dom.addClass(this, cls);	
			for(var n=0;n<label.length;n++){
				if(label[n]!=this){
					Dom.repalceClass(label[n], cls);
					box[n].style.display = "none";
				}else{
					box[n].style.display = "block";
				}
			}
		};
	}
}


window.Dom = Dom;

//常用方法释放到全局
/**
 * @class window 全局对象
 * @singleton
 */
/**
 * {@link Dom#_} 释放至全局
 * @method _
 * @param {string} s 元素ID
 * @return {HTMLElement}
 */
window._ = Dom._;

/**
 * {@link Dom#getByTagName} 释放至全局
 * @method _t
 * @param {HTMLElement} parent 父结点
 * @param {string} tag 标签名称
 * @return {HTMLElements} 
 */
window._t = Dom.getByTagName;
/**
 * {@link Dom#getByClass} 释放至全局
 * @method _c
 * @param {string} searchClass 类名
 * @param {HTMLElement} node 父结点
 * @param {string} tag 标签名称(可选)
 * @return {HTMLElements}
 */
window._c = Dom.getByClass;

/**
 * {@link Dom#addEvt} 释放至全局
 * @method addEvt 
 * @param {HTMLElement} elm
 * @param {string} en 事件名
 * @param {Function} func 监听函数
 */
window.addEvt = Dom.addEvt;

/**
 * {@link Dom#tabSwitch} 释放至全局
 * @method tabSwitch 
 * @param {HTMLElement} elm
 * @param {string} en 事件名
 * @param {Function} func 监听函数
 */
window.tabSwitch = Dom.tabSwitch;



Dom.getOffset = function(elm) {
	var l = elm.offsetLeft,
		t = elm.offsetTop,
		p = elm;
	while( p = p.offsetParent ) {
		l += p.offsetLeft;
		t += p.offsetTop;
	}
	return {l: l, t: t};
}

/*   旧版，未使用
Dom.showDropList = function ( id, url, evt, opt) {
	evt = 'click';
	opt = opt || {};
	var w = opt.w ? opt.w : 145;
	//url , cls , evt , callback
	var elm = typeof id == 'string' ? Dom._(id) : id;
	if( !elm ) 
		return false;
		
	var icon =  _t(elm, 'i'),
		div = _t(elm, 'div');
	if( icon[0] && div[0] ) {
		icon = icon[0];
		div = div[0];
	}else 
		return false;

	var cls = opt.cls || 'on';
	var zIndex = opt.zIndex || 9999;
	var align = opt.align || 'left';
	var div2PaddingWidth = opt.div2PaddingWidth || 16;

	var div2 = document.createElement('DIV');
	div2.className = 'dropList';
	div2.innerHTML = div.innerHTML;
	div2.style.cssText = 'display: none; width: ' + w + 'px; z-index: '+ zIndex;
	
	try {
		document.body.appendChild(div2);
	}catch(e){}
	var reg = new RegExp('^ *'+cls+'(?:[ ]*|\\b)+','ig');
	addEvt(elm, evt, function(e){
		e.preventDefault && e.preventDefault();
		if( reg.test(elm.className) ){
			div2.style.display = 'none';
			Dom.repalceClass(elm, cls);
			return false;
		}
		Dom.addClass(elm, cls);
		var xy = Dom.getOffset(elm);
		var isIE7 = document.documentMode && document.documentMode == '7';

		if( align == 'right' ){
			xy.l = xy.l - ( w - elm.offsetWidth + div2PaddingWidth );
		}
		div2.style.left = xy.l + (isIE7 ? -1 : 0) + 'px';
		div2.style.top = xy.t + elm.offsetHeight +2+ 'px';
		
		div2.style.display = 'block';	
		
		if( url != null && div2.innerHTML == "" ){
			div2.innerHTML = "正在加载...<em></em>";
			
			ajaxGet(url, function(r){
				div2.innerHTML = r;

				var em = _t(div2, 'em')[0];
				em.style.width = elm.offsetWidth - 2 + 'px';
				if( align == 'right' )
					em.style.left = w + div2PaddingWidth - elm.offsetWidth + 'px';

				opt.callback && opt.callback(div2);
			});
		}else {
			var em = _t(div2, 'em')[0];
				em.style.width = elm.offsetWidth - 2 + 'px';
			if( align == 'right' )
				em.style.left = w + div2PaddingWidth - elm.offsetWidth  + 'px';
		}
		return false;
	});
}
*/

Dom.showDropList = function( id, url, evt, opt ){
	var doc = document;
	if( !doc.body.getElementsByClassName )
		return false;
		
	var topBar = doc.body.getElementsByClassName('top');
	if( topBar.length )
		topBar = topBar[0];
	
	var elm = typeof id == 'string' ? Dom._(id) : id;
	if( !elm ) 
		return false;
		
	var div = _t(elm, 'div');
	if( div[0] ) {
		div = div[0];
	}else 
		return false;
	
	var div2 = doc.createElement('DIV');
	div2.className = 'cityBox';
	div2.innerHTML = div.innerHTML;
	div2.style.display = 'none';
	
	doc.body.insertBefore(div2,topBar.nextSibling);
	
	addEvt(elm, 'click', function(){
		var cityName = '@';
		try {
			cityName = _t(elm, 'span')[0].innerHTML.match(/[\u4e00-\u9FBF]+/g)[0];
		}
		catch(e){}
		
		var citys = _t(div2,'a');
		for(var i=0;i<citys.length;i++){
			if( citys[i].innerHTML.indexOf(cityName) != -1 )
				citys[i].className = 'on';	
			else
				citys[i].className = '';	
		}
		
		if( div2.style.display == 'none' ){
			div2.style.display = 'block';
		}
		else {
			div2.style.display = 'none';
		}
	});
}

window.tabSwitch = Dom.webkitSlider = Dom.tabSwitch;
/* 鉴于滑动有一些兼容问题，暂时去掉滑动
Dom.webkitSlider = function(tabsParentId, consParentId, opt) {
	var E = window.E;
	var tabsParent = typeof tabsParentId == 'string' ? Dom._(tabsParentId) : tabsParentId,
		tabs = tabsParent.children,
		consParent = typeof consParentId == 'string' ? Dom._(consParentId) : consParentId,
		cons = consParent.children;
		
	var len = tabsParent.children.length;
	var c = 0;
	var timer = null, duration = 230, ts = 23, frames = duration/ts;

	function initView() {
		for(var j=tabs.length-1;j>=0;j--)
			tabs[j].setAttribute('c', j);
			
		var outerDiv = document.createElement('DIV');
		outerDiv.style.cssText = 'width: 100%; overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical';
		consParent.parentNode.insertBefore(outerDiv, consParent);
		outerDiv.appendChild(consParent);
		
		consParent.style.cssText = 'width:' + len +'00%; overflow: hidden; display: -webkit-box; -webkit-box-flex: 1';
		for(var i=0;i<cons.length;i++) {
			cons[i].style.cssText = 'display: block; width:'+ 100/len +'%; overflow: hidden;' + (i != c ? 'height: 30px;' : '');
		}
	}
	initView('cagCon');
	var currentN = _('currentN');
	function  sliderTo(n) {
		if( n < 0 || n >= len )
			return false;

		if( timer )
			return false;
		
		var self = this,
			ew = self.offsetWidth/len,
			curML = -1*c*ew,
			tarML = -1*n*ew;
			
		Dom.repalceClass(tabs[c], 'on');
		Dom.addClass(tabs[n], 'on');

		cons[c].style.cssText = 'display: block; width:'+ 100/len +'%; overflow: hidden; height: 30px';
		cons[n].style.height = 'auto' ;
		
		c = n;
		
		var hstep = (tarML - curML) / (duration / frames);
		var maxStep = ew/5, minStep = ew/10;
		if (Math.abs(hstep) > maxStep)
			hstep = hstep > 0 ? maxStep : -1*maxStep;
		if (Math.abs(hstep) < minStep)
			hstep = hstep > 0 ? minStep : -1*minStep;
		
		timer = setInterval(function () {
			if (Math.abs(curML + hstep - tarML) <= 30) {
				curML = tarML;
				consParent.style.marginLeft = tarML + 'px';
				clearInterval(timer);
				timer = null;
			} else {
				curML += hstep;
				consParent.style.marginLeft = curML + 'px';
			}
		}, ts);
	}
	
	function _passParma(tab){
		return function(e){
			var tab_n = tab.getAttribute('c');
			if( c != tab_n )
				sliderTo.call(consParent, tab_n);
		}
	}
	for(var i=0;i<len;i++){
		Dom.addEvt(tabs[i], 'click',  _passParma(tabs[i]));
	}

	E.bind(consParent, 'swipeRight', function(e){
		
		if( c-1 < 0 )
			return false;
		sliderTo.call(this,c-1);
	});
	E.bind(consParent, 'swipeLeft', function (e) {
		if( c > len-1 ) {
			return false;
		}
		sliderTo.call(this,parseInt(c)+1);
	});
}
*/

//显示更多处理
Dom.setListMore = function(ID, count, opt) {
	opt = opt || {};
	
	var mList1 = _(ID);
	var cls = opt.listClass || 'productList',
		ul = _c(cls, mList1)[0],
		listMore = _c('listMore', mList1, 'div')[0];
	var lis = ul.children,
		len = lis.length,
		page = 0,
		count = count || 5;
	if( len <= count ){
		removeLM();
		return false;
	}
	
	function removeLM(){
		listMore.parentNode.removeChild(listMore);
	}
	for(var i=0;i<len;i++){
		if( i >= count )
			lis[i].style.display = 'none';
	}
	var timer2 = null;
	addEvt(listMore, 'click', function(e){
		if( timer2 ) 
			return false;
		
		var tar = e.srcElement || e.target;
		if( tar.nodeName.toUpperCase() == 'A' ){
			document.body.scrollTop  = document.documentElement.scrollTop = 0;
			return false;
		}
		
		if( listMore.innerHTML == '&nbsp;<a href="#" class="btn_ToTop">回顶部</a>' )
			return false;
			
		listMore.innerHTML = '<img src="/wap2012/images/loading5.gif" alt="" />';
		timer2 = setTimeout(function(){
			if( (page+1)*count >= len ){
				listMore.innerHTML = '&nbsp;<a href="#" class="btn_ToTop">回顶部</a>';
				timer2 = null;
				return false;
			}
			page++;
			for(var i=0;i<len;i++){
				if( i < (page+1)*count )
					lis[i].style.display = '';
			}
			if( (page+1)*count >= len ){
				listMore.innerHTML = '&nbsp;<a href="#" class="btn_ToTop">回顶部</a>';
			}else {
				listMore.innerHTML = [
				    '显示更多',
				    '<em><span class="on"></span><span class=""></span><span class=""></span></em>',
					'<a href="#" class="btn_ToTop">回顶部</a>'
				].join('');
			}
			timer2 = null;
		}, 500 + Math.random()*1500 >> 0);
	});
}
window.setListMore = Dom.setListMore;

Dom.lockUI = function(){
	var maskBox = _('maskBox');
	if( !maskBox ){
		maskBox = document.createElement('div');
		maskBox.id = 'maskBox';
		maskBox.className = 'mask-box';
		maskBox.innerHTML = '<div class="mask"></div><div class="loading"></div>';
		document.body.appendChild(maskBox);
	}else {
		maskBox.style.display = 'block';
	}
};

Dom.unlockUI = function(){
	var maskBox = _('maskBox');
	if( maskBox ){
		maskBox.style.display = 'none';
	}
}

})();